<template>
  <div class="container">
    <n-tabs v-model:tab="activeTab">
      <n-tab-pane name="all" tab="全部分类">
        <n-space vertical size="large">
          <n-space>
            <n-button @click="fetchApis('all', 0)" type="primary">最新</n-button>
            <n-button @click="fetchApis('all', 1)">最热</n-button>
          </n-space>

          <n-row gutter="12">
            <n-col :span="6" v-for="item in items" :key="item.id">
              <n-card class="card" style="height: 460px">
                <template #header>
                  <n-space style="height: 196px">
<!--                    <n-tag  :style="tagStyle" :visibility="!isThisMonth(item.createTime)?'hidden':'visible'">{{-->
<!--                        getTagText(item.createTime)-->
<!--                      }}</n-tag>-->
                    <n-tag :style="[tagStyle, { visibility: isThisMonth(item.createTime) ? 'visible' : 'hidden' }]">{{ getTagText(item.createTime) }}</n-tag>
                    <n-avatar round :src="item.imageSrc" class="card-image"></n-avatar>
                  </n-space>
                </template>
                <div class="card-content">
                  <h4>{{ item.name }}</h4>
                  <div style="height: 45px">
                    <p>{{ item.description }}</p>
                  </div>
                  <div style="height: 28px">
                    <div
                      class="tags"
                      :hidden="!(item.interfaceLabelList && item.interfaceLabelList.length)"
                    >
                      <n-tag
                        v-for="(tag, index) in item.interfaceLabelList"
                        :key="index"
                        style="margin-right: 4px"
                        >{{ tag }}</n-tag
                      >
                    </div>
                  </div>
                </div>
                <n-space class="card-footer">
<!--                  <n-button type="primary" :href="item.url">立即使用</n-button>-->
                  <n-button type="primary" @click="onlineCall(item.id)">在线调用</n-button>
                  <n-button :href="item.docLink">技术文档</n-button>
                </n-space>
              </n-card>
            </n-col>
          </n-row>
        </n-space>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script>
import { ref } from 'vue'
import { NButton, NCard, NCol, NRow, NSpace, NTag, NAvatar, NTabs, NTabPane } from 'naive-ui'
import apiClient from '@/api/axios.ts'
import { useRouter } from 'vue-router'

export default {
  components: {
    NButton,
    NCard,
    NCol,
    NRow,
    NSpace,
    NTag,
    NAvatar,
    NTabs,
    NTabPane
  },
  setup() {
    const activeTab = ref('all')
    const items = ref([])
    const isLoading = ref(false)
    const router = useRouter();

    const fetchApis = async (type, val) => {
      isLoading.value = true
      try {
        console.log('Fetching APIs with type:', type, 'and val:', val)
        const response = await apiClient.post('/interfaceInfo/list/page', {
          pageSize: 10,
          current: 1,
          status: 0,
          sortField: 'createTime',
          sortOrder: 'descend'
        })
        console.log('API Response:', response)
        const responseData = response.data
        if (responseData.code === 0) {
          items.value = responseData.data.records.map((item) => ({
            ...item,
            imageSrc: 'https://cdn.free-api.com/a2541-851n9.webp', // 默认图片链接，可以根据需要更改
            docLink: `/doc/${item.id}` // 假设文档链接是这样生成的
          }))
          console.log('首页从后端读取的接口信息数据:' + items.value)
        } else {
          console.error('查询接口信息列表失败，返回的状态码:', responseData.code)
        }
      } catch (error) {
        console.error('查询接口信息列表失败:', error)
      } finally {
        isLoading.value = false
      }
    }

    const currentMonth = new Date().getMonth() + 1
    const currentYear = new Date().getFullYear()

    const isThisMonth = (createTime) => {
      const uploadDate = new Date(createTime)
      const uploadMonth = uploadDate.getMonth() + 1
      const uploadYear = uploadDate.getFullYear()
      return uploadMonth === currentMonth && uploadYear === currentYear
    }

    const getTagText = (createTime) => {
      const uploadDate = new Date(createTime)
      const uploadMonth = uploadDate.getMonth() + 1
      return `${uploadMonth}月上新`
    }

    const tagStyle = {
      backgroundColor: '#00bdfe',
      color: '#fff',
      padding: '5px 10px',
      borderRadius: '15px',
      fontSize: '14px',
      fontWeight: 'bold',
      textShadow: '1px 1px 2px rgba(0, 0, 0, 0.3)'
    }

    const onlineCall = (id) => {
      console.log("首页点击接口在线使用时由路由传递的id参数:id = " + id)
      router.push({ name:'OnlineInvoke', params: { interfaceId: id } });
    };
    return {
      activeTab,
      items,
      fetchApis,
      isThisMonth,
      getTagText,
      tagStyle,
      isLoading,
      onlineCall
    }
  },
  mounted() {
    this.fetchApis('all', 0)
  }
}
</script>

<style scoped>
.container {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  box-sizing: border-box;
  width: 100%;
}

@media (max-width: 1280px) {
  .container {
    padding: 1rem;
  }
}

.card {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  border: 1px solid #00bdfe; /* 设置统一的边框 */
  border-radius: 10px; /* 可选：添加圆角 */
  padding: 16px; /* 可选：添加内边距 */
}

.card-image {
  width: 100%;
  height: 150px; /* 调整图片高度 */
  object-fit: cover;
}

.card-content {
  flex-grow: 1;
  margin-bottom: 16px; /* 添加下边距，避免内容和底部按钮重叠 */
}

.card-footer {
  margin-top: auto;
}
</style>
